<?php

// ------------------------------
// Caractéristiques du module
// ------------------------------
unset($module);
$module = array(
    "titre" => "Gestion des libérations",
    "urldest" => $SCRIPT_NAME . "?page=liste_liberations",
    "recherche" => array("engin" => true),
    "jeton" => $jeton,
    "opradmin" => "Ajouter une libération",
    "fenetre" => array(
        "nom" => "liste_liberations",
        "titre" => "titre",
        "largeur" => "1024",
        "hauteur" => "500",
        "champs" => array("lemploye") //, "lpresentation", "lnom", "lprenom", "ladresse1", "ladresse2", "lville", "lcodepostal", "ltelephone", "lemail", "lmembreca", "lnoemployeur", "lnumero")
    ),
    "msgajoutbouton" => "Ajout de la libération",
    //"actionajoutbouton" => "Ajouter la lib�ration",
    "msgmodifbouton" => "Modification de la libération",
    //"actionmodifbouton" => "Modifier la fiche de l'employ�",
    "nombre_a_afficher" => array(
        0 => array("refid" => 15, "valeur" => 15),
        1 => array("refid" => 30, "valeur" => 30),
        2 => array("refid" => 45, "valeur" => 45),
        3 => array("refid" => 60, "valeur" => 60),
        4 => array("refid" => 120, "valeur" => 120),
        5 => array("refid" => 240, "valeur" => 240)
    ),
    "lientri" => true,
    "entete" => array(
        1 => array("Employé" => "concat(employes.nomfamille,employes.prenom)", "largeur" => "130px"),
        2 => array("Type" => "liberations.typeoperation", "largeur" => "78px"),
        3 => array("Date de libération" => "ligneliberations.dateliberation", "largeur" => "141px"),
        4 => array("Article" => "articles.noarticle", "largeur" => "65px"),
        5 => array("Commentaire" => "ligneliberations.commentaire", "largeur" => "204px"),
        6 => array("Durée" => "duree.duree", "largeur" => "61px"),
        7 => array("Lieu" => "ligneliberations.lieu", "largeur" => "79px"),
        8 => array("Assumer par" => "ligneliberations.quipaye", "largeur" => "105px"),
        9 => array("Paiement" => "ligneliberations.paiement", "largeur" => "84px"),
        10 => array("En date du" => "ligneliberations.datepaiement", "largeur" => "90px"),
        11 => array("<img alt=\"Save\" src=\"../images/icones/icones_12.png\">" => "-1", "largeur" => "23px", "droit" => array("gestion_site" => "Oui")),
        12 => array("<img alt=\"Pdf\" src=\"../images/pdficon_small.gif\">" => "-1", "largeur" => "22px")
    ),
    "msg" => array(
        "maj_ok" => "Création de la libération effectuée avec succès.",
        "maj_echec" => "L'opération de création de la libération a échouée",
        "rech_ok" => "La recherche a réussie.",
        "rech_echec" => "La recherche a été infructueuse ou a échouée.",
        "employeur_invalide" => "Employeur introuvable ou inconnu.",
    )
);

session_start();

require (__DIR__ . '/vendor/autoload.php');
require_once("lib/libconfig.inc.php");
require_once("lib/libsession.inc.php");
require_once("lib/libfonctions.inc.php");
require_once("lib/libmysql.inc.php");
require_once("lib/libencode.inc.php");
require_once("lib/libforms.inc.php");
require_once("lib/libcourriel.inc.php");
require_once("lib/libliberations.inc.php");
require_once("lib/lib2fa.inc.php");

ini_set('display_errors', 'off');
//Encodage des caractères
header('Content-Type: text/html; charset=$ENCODAGE');

//Pour test local avec des appels directs, transformer les INPUT_POST en INPUT_GET
//INPUT_POST
//INPUT_GET

$SCRIPT_NAME = "index2.php";
$jeton = filter_input(INPUT_POST, "jeton");
$rsearch1 = filter_input(INPUT_POST, "prm1");

if (!empty($rsearch1)) {

    if ($rsearch1 == "-1" || intval($rsearch1) > 0) {

        unset($cpt, $vide);
        $cpt = 0;
        if (intval($rsearch1) > 0) {
            unset($sqlparam);
            $sqlparam["table"][] = "liberations";
            $sqlparam["table"][] = "ligneliberations";
            $sqlparam["table"][] = "employes";
            $sqlparam["table"][] = "articles";
            $sqlparam["table"][] = "employeurs";
            $sqlparam["table"][] = "duree";
            $sqlparam["join"][] = "ligneliberations.refliberation = liberations.refliberation";
            $sqlparam["join"][] = "employes.refemploye = liberations.refemploye";
            $sqlparam["join"][] = "ligneliberations.refarticle = articles.refarticle";
            $sqlparam["join"][] = "employes.refemployeur=employeurs.refemployeur";
            $sqlparam["join"][] = "ligneliberations.duree=duree.refduree";
            $sqlparam["champs"][] = "liberations.refliberation";
            $sqlparam["champs"][] = "ligneliberations.refligneliberation";
            $sqlparam["champs"][] = "employes.numemploye";
            $sqlparam["champs"][] = "CONCAT(employes.prenom,' ',employes.nomfamille) as nomemploye";
            $sqlparam["champs"][] = "liberations.typeoperation";
            $sqlparam["champs"][] = "UNIX_TIMESTAMP(liberations.datedemande) as datedemande";
            $sqlparam["champs"][] = "unix_timestamp(ligneliberations.dateliberation) as dateliberation";
            $sqlparam["champs"][] = "duree.duree";
            $sqlparam["champs"][] = "articles.noarticle";
            $sqlparam["champs"][] = "ligneliberations.commentaire";
            $sqlparam["champs"][] = "ligneliberations.lieu";
            $sqlparam["champs"][] = "ligneliberations.quipaye";
            $sqlparam["champs"][] = "ligneliberations.paiement";
            $sqlparam["champs"][] = "IF(ligneliberations.paiement=2,UNIX_TIMESTAMP(ligneliberations.datepaiement),'') as datepaiement";
            $sqlparam["where"][] = sprintf("liberations.refliberation=%d", $rsearch1);
            unset($resultlib);
            //$sqlparam["debug"]=2;
            $resultlib = executerRequeteSql($sqlparam);
            $cpt = count($resultlib) - 1;
            $vide = false;
        } else {
            $cpt = 0;
            $vide = true;
            $resultlib = array();
        }

        //Si syndicat régionaux, on limite l'accès aux articles.
        unset($sqlparam);
        $sqlparam["table"][] = "articles";
        $sqlparam["champs"][] = "refarticle";
        $sqlparam["champs"][] = "noarticle";
        if ($_SESSION['gestion_site'] == 'Non') {
            $sqlparam["where"][] = "noarticle='7.04' OR noarticle='7.09'";
        }
        unset($resultart);
        $resultart = executerRequeteSql($sqlparam);

        //Lecture des durées de temps
        unset($sqlparam);
        $sqlparam["table"][] = "duree";
        $sqlparam["champs"][] = "refduree";
        $sqlparam["champs"][] = "duree";
        unset($resultduree);
        $resultduree = executerRequeteSql($sqlparam);

        // Formulaire de saisie
        print "    <table width='100%' border='0' >\n";
        print "    <tr>\n";
        print "    <td align='center' width='100%'>\n";
        print "    <div style='background:#f2f6f7'>\n";

        print "    <form action='" . $SCRIPT_NAME . "?page=liste_liberations&jeton=" . $jeton . "' method='post' id='frmModif' name='frmModif' "; //>\n";
        if (isset($param["validation"])) {
            print " onSubmit='return ValidationFormulaire();'";
        }
        print "    autocomplete='off'>\n";
        print "    <table width='100%'>\n";
        print "    <tr>\n";
        print "    <td colspan='2'>\n";
        print "    <table width='100%'>\n";
        print "    <tr>\n";
        print "    </tr>\n";
        print "    </table>\n";
        print "    </td>\n";
        print "    </tr>\n";

        print "<INPUT TYPE='hidden' name='action'>\n";
        print "<INPUT TYPE='hidden' name='noliberation'>\n";
        print "<table width='100%' border='0'>\n";
        print "<tr>\n";
        print "<td valign=top style='width:300px;'>Type d'op&eacute;ration : </td>\n";
        print "<td style='width:305px;'>\n";
        if ($vide) {
            print "<table style='width:265px; padding-left:20px; padding-right: 20px; border:1px solid #cfcfcf;'>\n";
            print "<tr>\n";
            print "<td>\n";
            print "<label for='opr1'>\n";
            print "<input style='margin-right:10px;' type='radio' id='opr1' name='ltypeopr' value='1'> Demande&nbsp;&nbsp;\n";
            print "</label>\n";
            print "<label for='opr2'>\n";
            print "<input style='margin-right:10px;' type='radio' id='opr2' name='ltypeopr' value='2'> Annulation&nbsp;&nbsp;\n";
            print "</label>\n";
            print "</td>\n";
            print "</tr>\n";
            print "</table>\n";
        } else {
            unset($vtypeopr);
            $vtypeopr = ($resultlib[0]["typeoperation"] == 1) ? "Demande" : "Annulation";
            print $vtypeopr;
            print "<input type='hidden' id='opr' name='ltypeopr' value='" . $resultlib[0]["typeoperation"] . "'>\n";
            print "<input type='hidden' name='liberation' value='$rsearch1'>\n";
        }

        print "</td>\n";
        print "<td style='text-align:right; width:200px;'>\n";
        print "<INPUT class='styled vsolde' TYPE='button' VALUE='Voir le solde' id='vsolde' onclick='voirsolde();'>\n";
        print "<div style='position: relative; margin-left:85px;'>\n";
        print "<div class='voirsolde' id='voirsolde' style='display:none; padding:2px;'></div>\n";
        print "</div>\n";
        print "</td>\n";
        print "</tr>\n";
        print "<tr>\n";
        print "<td valign=top>\n";
        print "Employ&eacute; :\n";
        print "</td>\n";
        print "<td colspan='2'>\n";
        unset($condition1, $condition2, $condition3);
        $condition1 = "Recherche";
        $condition2 = "";
        $condition3 = date("Y-m-d");
        if (!$vide) {
            $condition1 = $resultlib[0]["nomemploye"];
            $condition2 = ($resultlib[0]["typeoperation"] == 2) ? "checked" : "";
            $condition3 = date("Y-m-d", $resultlib[0]["datedemande"]);
        }
        if ($vide) {
            print "<input type='text' value='$condition1' id='zonerecherche2' name='zonerecherche2' onfocus=\"this.value='';\">\n";
        } else {
            print ucfirst($condition1);
        }
        print "<input type='hidden' value='$condition2' id='lreference2' name='lreference'>\n";
        print "<div id='zoneresultats2' style='max-height:300px;'>\n";
        print "</div>\n";
        print "</td>\n";
        print "</tr>\n";
        print "<tr>\n";
        print "<td>Date de la cr&eacute;ation du document de lib&eacute;ration : </td>\n";
        print "<td colspan='2'>\n";
        if ($vide) {
            print "<INPUT TYPE='text' NAME='ldatecreation' id='datecreation' Value='$condition3'> (Format : AAAA-MM-JJ)\n";
        } else {
            print "$condition3";
            print "<INPUT TYPE='hidden' NAME='ldatecreation' id='datecreation' Value='$condition3'>";
        }
        print "</td>\n";
        print "</tr>\n";
        print "<tr>\n";
        print "<td colspan='3'>\n";

        print "<br>\n";

        //<!-- Il faut conserver 2 rangées pour cette table, l'entête et la seconde
        //qui sert de modèle pour l'insertion des rangées virtuelles subséquentes.-->
        print "<table id='liberations' cellspacing='0' style='width:100%; border-collapse:collapse; border:1px solid #cfcfcf;'>";
        print "<tbody>\n";
        print "<tr>\n";
        print "<th class='liberationsdetail'>Date de lib&eacute;ration</th>\n";
        print "<th class='liberationsdetail'>Article</th>\n";
        print "<th class='liberationsdetail'>Commentaire</th>\n";
        print "<th class='liberationsdetail'>Dur&eacute;e</th>\n";
        print "<th class='liberationsdetail'>Lieu</th>\n";
        print "<th class='liberationsdetail'>Assum&eacute;e par</th>\n";
        if (!$vide) {
            print "<th class='liberationsdetail'>Paiement</th>";
            print "<th class='liberationsdetail'>En date du</th>";
        } else {
            // Colonne visible seulement en mode ajout
            print "<th style=class='liberationsdetail'>&nbsp;</th>\n";
        }

        print "</tr>\n";

        // Boucle d'affichage des lignes de détail
        unset($x);
        $tableauid = array();
        for ($x = 0; $x <= $cpt; $x++) {

            unset($liberation);
            $liberation["refliberation"] = "";
            $liberation["date"] = "";
            $liberation["article"] = "";
            $liberation["commentaire"] = "";
            $liberation["duree"] = "";
            $liberation["lieu"] = "";
            $liberation["assumerpar"] = "";
            $liberation["paiement"] = "";
            $liberation["datepaiement"] = "";
            if (!$vide) {
                $liberation["refliberation"] = $resultlib[$x]["refliberation"];
                $liberation["date"] = date("Y-m-d", $resultlib[$x]["dateliberation"]);
                $liberation["article"] = $resultlib[$x]["noarticle"];
                $liberation["commentaire"] = htmlentities(stripslashes($resultlib[$x]["commentaire"]), ENT_QUOTES, $ENCODAGE);
                $liberation["duree"] = $resultlib[$x]["duree"];
                $liberation["lieu"] = htmlentities(stripslashes($resultlib[$x]["lieu"]), ENT_QUOTES, $ENCODAGE);
                $liberation["assumerpar"] = $resultlib[$x]["quipaye"];
                $liberation["paiement"] = $resultlib[$x]["paiement"];
                $liberation["datepaiement"] = ($resultlib[$x]["paiement"] == 2) ? date("Y-m-d", $resultlib[$x]["datepaiement"]) : "";
                $liberation["refligneliberation"] = $resultlib[$x]["refligneliberation"];
            }

            print "<tr class='ligne' id='ligne$x'>\n";
            print "<td class='liberationsdetail'>\n";
            print "<input name=\"ancdate[]\" value=\"" . $liberation["date"] . "\" id='idanc$x'\" type=\"hidden\">";
            print "<input name='datelib[]' style='min-width:80px;' value='" . $liberation["date"] . "' id='id$x' onblur=\"verifieDate('id$x','lart$x');\" onfocus='verifieinfo();' >";
            print "<img alt='Calendrier'  src='images/calendar.gif' class='calendrier' id='butdate$x' onclick=\"calendrier('id$x');\">\n";
            print "</td>\n";
            print "<td class='liberationsdetail'>\n";
            print "<select name='larticle[]' id='lart$x' onfocus='verifieinfo();' onblur=\"reponseBoolDate=true;verifieDate('id$x','lart$x');\" >\n";
            print "<option>--------</option>\n";

            if (isset($resultart) && is_array($resultart) && count($resultart) > 0) {
                foreach ($resultart as $clef => $champs) {
                    unset($selected);
                    $selected = "";
                    if ($champs["noarticle"] == $liberation["article"]) {
                        $selected = "selected";
                    }
                    print "<option $selected value=\"" . $champs["refarticle"] . "\">" . $champs["noarticle"] . "</option>";
                }
            }
            print "</select>\n";
            print "</td>\n";
            print "<td class='liberationsdetail'>\n";
            print "<input name='commentaire[]' id='com$x' value=\"" . $liberation["commentaire"] . "\" onfocus='verifieinfo();' >\n";
            print "</td>\n";
            print "<td class='liberationsdetail'>\n";
            print "<select name='lduree[]' id='ldur$x' onfocus='verifieinfo();' >\n";
            print "<option>------</option>\n";

            if (isset($resultduree) && is_array($resultduree) && count($resultduree) > 0) {
                foreach ($resultduree as $clef => $champs) {
                    unset($selected);
                    $selected = "";
                    if ($champs["duree"] == $liberation["duree"]) {
                        $selected = "selected";
                    }
                    print "<option $selected value=\"" . $champs["refduree"] . "\">" . $champs["duree"] . "</option>";
                }
            }

            print "</select>\n";
            print "</td>\n";
            print "<td class='liberationsdetail'>\n";
            print "<input name='lieu[]' value=\"" . $liberation["lieu"] . "\" id='lie$x' onfocus='verifieinfo();' >\n";
            print "</td>\n";
            print "<td class='liberationsdetail'>\n";
            print "<select NAME='lassumerpar[]' id='las$x' onfocus='verifieinfo();' >\n";
            print "<option>--------</option>\n";
            unset($selected1, $selected2);
            $selected1 = "";
            $selected2 = "";
            if ($liberation["assumerpar"] == "Syndicat") {
                $selected1 = "selected";
            } elseif ($liberation["assumerpar"] == "Employeur") {
                $selected2 = "selected";
            }
            print "<option $selected1 value='Syndicat'>Syndicat</option>\n";
            print "<option $selected2 value='Employeur'>Employeur</option>\n";
            print "</select>\n";
            print "</td>\n";
            if (!$vide) {
                print "<td class='liberationsdetail'>";
                print "<select NAME=\"lpaiement[]\" id=\"lpa$x\" onchange=\"creeDatePaiement('lpa$x','datepaiement$x');\"\">";
                print "<option value=\"0\">--------</option>";
                unset($condition1, $condition2);
                $condition1 = ($liberation["paiement"] == "1") ? "Selected" : "";
                $condition2 = ($liberation["paiement"] == "2") ? "Selected" : "";
                print "<option value=\"1\" $condition1>Non</option>";
                print "<option value=\"2\" $condition2>Oui</option>";
                print "</td>\n";
                print "<td class='liberationsdetail'>";
                print "<input name=\"datepaiement[]\" id=\"datepaiement$x\" size=\"10\" maxlength=\"10\" type=\"text\"  readonly=\"readonly\" value=\"" . $liberation["datepaiement"] . "\">";
                print sprintf("<input type='hidden' id='ligneliberation$x' name='ligneliberation[]' value='%d'>", $liberation["refligneliberation"]);
                print "</td>\n";
            } else {
                // La suppression de ligne seulement en mode ajout d'une libération
                print "<td class='liberationsdetail'>\n";
                print "<input type='button' class='supprimer' onclick='supprimeLigne(this);' value='' id='$x'>\n";
                print "</td>\n";
            }
                       
            $tableauid[] = "$(\"#id$x\").datepicker({
                  autoSize: true,
                  onSelect:function(){
                     reponseBoolDate=true;
                     verifieDate('id$x','lart$x');
                  }
               });\n
               $(\"#id$x\").datepicker(\"hide\");\n";
            print "</tr>\n";
        }
        // Fin de la boucle
        print "</tbody>\n";
        print "</table>\n";
        print "<script type=\"text/javascript\">$(document).ready(function() {\n";
        if ($vide) {
            print "
         // Calendrier pour la date de demande
            $( \"#datecreation\" ).datepicker({
               showOn: \"button\",
               buttonImage: \"images/calendar.gif\",
               buttonImageOnly: true
            });\n";
        }
        foreach ($tableauid as $clef) {
            print $clef;
        }
        print "});</script>";

        // L'ajout de ligne seulement en mode ajout d'une libération
        if (!$vide) {
            print "<div style='height:25px;'></div>\n";
        } else {
            print "<div class='user' style='cursor:pointer;' tabindex='0' onclick=\"addRow('liberations');\">Ajouter une ligne</div>\n";
        }
        print "<div style='width:auto; text-align:center;'>\n";
        print "<INPUT class='styled' TYPE='button' VALUE='Aper&ccedil;u' onclick='apercuLiberation();'>\n";
        if ($vide) {
            print "<INPUT class='styled' TYPE='button' VALUE='Accepter et imprimer' onclick='ValidationFormulaire(this.value);'>\n";
            print "<INPUT class='styled' TYPE='button' VALUE='Accepter et envoyer par courriel' onclick='ValidationFormulaire(this.value);'>\n";
        } else {
            print "<INPUT class='styled' TYPE='button' VALUE='Modifier' onclick='ValidationFormulaire(this.value);'>\n";
            print "<INPUT class='styled' TYPE='button' VALUE='Modifier et imprimer' onclick='ValidationFormulaire(this.value);'>\n";
            print "<INPUT class='styled' TYPE='button' VALUE='Annuler la libération' onclick='AnnuleLiberation(this.value,".$liberation["refliberation"] .");'>\n";
        }

        if ($vide) {
            print "<INPUT class='styled' TYPE='button' VALUE='Effacer' onclick='recommencer();'>";
        }
        unset($titretemp);
        //$datepaiement = ($champs[6] == 2) ? date("Y-m-d", $champs[8]) : "&nbsp;";
        if (isset($module["actionajoutbouton"])) {
            $titretemp = $module["actionajoutbouton"];
        }
        $titretemp = '';

        print "</div>\n";
        print "   <tr>\n";
        print "   <td colspan='3' style='height:50px; text-align:center;'>\n";
        $style = "font-size:10pt; font-family:arial, helvetica, sans-serif; margin-left:5px; margin-right:5px; text-align:center;";
        //TODO
        //Suspendu pour l'instant, je ne vois pas d'assignation de la variable $titre.....
        //SG 2023-09-30
        /*
        if (is_array($titre)) {
            foreach ($titre as $clef) {
                print "<input style='$style' type=\"submit\" id='boutonaction' name=\"action\" value=\"" . $clef . "\">&nbsp;\n";
            }
        } else {
            if ($titre != '') {
                print "   <input style='$style' type=\"submit\" id='boutonaction' name=\"action\" value=\"" . $titre . "\">\n";
            }
        }
        */
        print "<input class='styled' type=\"button\" id='boutonaction' value=\"Annuler\" onclick='fermerfenetremodale();'>&nbsp;\n";
        print "   </td>\n";
        print "   </tr>\n";
        print "   </table>\n";
        print "   </form>\n";
        print "   </div>\n";
        print "   </td>\n";
        print "   </tr>\n";
        print "   </table>\n";

        //fenetremodalefin($titretemp);
        ?>
        <script>
            $(document).ready(function () {
                // Paramètres pour la seconde zone de recherche
                $("#zonerecherche2").focus(function () {
                    if ($("#zonerecherche2").val() === 'Recherche') {
                        $("#zonerecherche2").val('');
                    }
                });
                $("#zonerecherche2").blur(function () {
                    $("#zoneresultats2").slideUp();
                });

                $("#zonerecherche2").keyup(function () {
                    var SearchText = $("#zonerecherche2").val();
                    if (SearchText.length > 0) {
                        $("#zoneresultats2").load("ajaxsearch.php", {zonerecherche: SearchText, id: 2});
                        $("#zoneresultats2").slideDown();
                    } else {
                        $("#zoneresultats2").slideUp();
                    }
                });
                $("#zoneresultats2").slideUp();
            });
        </script>
        <?php

    }
}
